<template>
  <div v-loading="loadingVisible" class="login">
    <el-card class="loginCard">
      <p class="loginTitle">小高后台管理系统</p>
      <el-form :model="formData" :rules="formRules" ref="formRef">
        <el-form-item prop="username">
          <el-input v-model="formData.username" autocomplete="off" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" show-password v-model="formData.password" autocomplete="off" placeholder="请输入密码"
            clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { loginReq } from '@/api/login.js'
import { setToken, removeToken } from '@/utils/token.js'

export default {
  data() {
    return {
      formData: {
        username: '',
        password: ''
      },
      formRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      loadingVisible: false
    }
  },
  methods: {
    submitForm() {
      this.$refs.formRef.validate((isValid) => {
        if (isValid) {
          this.loadingVisible = true
          console.log("formData", this.formData)
          loginReq(this.formData).then(res => {
            if (res.code === 200) {
              // 移除之前的token
              removeToken()
              // 存储新的token
              setToken(res.data)
              success("登录成功！")
            }
          }).finally(() => { this.loadingVisible = false })
        }
      })
    }
  },
}
</script>

<style>
.login {
  background-image: url("../images/login-background.jpg");
  background-size: cover;
  height: 100vh;
  position: relative; /* 父容器设置为相对定位 */
}

.loginCard{
  height: 300px;
  width: 300px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.loginTitle{
  text-align: center;
  font-weight: bold;
  font-size: x-large;
}
</style>
